var Package = {};

Package.TYPE_HANDSHAKE = 1;
Package.TYPE_HANDSHAKE_ACK = 2;
Package.TYPE_HEARTBEAT = 3;
Package.TYPE_DATA = 4;
Package.TYPE_KICK = 5;

Package.encode = function(type, body) {
    var length = body ? body.length: 0;
    var buffer = new Uint8Array(PKG_HEAD_BYTES + length);
    var index = 0;
    buffer[index++] = type & 0xff;
    buffer[index++] = (length >> 16) & 0xff;
    buffer[index++] = (length >> 8) & 0xff;
    buffer[index++] = length & 0xff;
    if (body) {
        copyArray(buffer, index, body, 0, length);
    }
    return buffer;
};

Package.decode = function(buffer) {
    var bytes = new Uint8Array(buffer);
    var type = bytes[0];
    var index = 1;
    var length = ((bytes[index++]) << 16 | (bytes[index++]) << 8 | bytes[index++]) >>> 0;
    var body = length ? new Uint8Array(length) : null;
    copyArray(body, 0, bytes, PKG_HEAD_BYTES, length);
    return {
        'type': type,
        'body': body
    };
};